package demo011;

import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class SocketServer {
	static SocketServer me =new SocketServer();
	public static void main(String[] args) throws Exception {
	    // 监听指定的端口
	    int port = 55533;
	    ServerSocket server = new ServerSocket(port);
	    
	    
	    // server将一直等待连接的到来
	    System.out.println("server将一直等待连接的到来");
	    Socket socket = server.accept();
	    // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
	    InputStream inputStream = socket.getInputStream();
	    OutputStream outStream=socket.getOutputStream();
	    byte[] bytes = new byte[1024];
	    int len;
	    StringBuilder sb = new StringBuilder();
	    while ((len = inputStream.read(bytes)) != -1) {
	      //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
	      sb.append(new String(bytes, 0, len,"UTF-8"));
	    }
	    System.out.println("get message from client: " + sb);
	    
	    //接收后发送
		
	    StringBuffer error = new StringBuffer();
		error.append("HTTP /1.1 400 file not found /r/n");
		error.append("Content-Type:text/html \r\n");
		error.append("Content-Length:20 \r\n").append("\r\n");
		error.append("<h1 >File Not Found..</h1>");
		try {
			outStream.write(error.toString().getBytes());
			outStream.flush();
			outStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	    inputStream.close();
	    outStream.close();
	    socket.close();
	    server.close();
	  }
	
	private void ShowFrame(){
		JFrame f=new JFrame("窗口标题");    //创建窗体对象并赋标题参数
        f.setSize(200,100);    //设置窗体大小
        f.setBackground(Color.WHITE);    //设置背景颜色
        f.setLocation(300,200);    //设置窗体显示位置
        f.setVisible(true);    //显示窗体
        
        JButton btnSend =new JButton();
        btnSend.setText("发送");
        btnSend.setSize(100, 20);
//        btnSend.addActionListener(l);
        JTextField txtContent =new JTextField();
        txtContent.setSize(100, 20);
        txtContent.setBackground(Color.BLUE);
        
        f.add(btnSend);
        f.add(txtContent);
	}

}
